<template>
  <basic-container class="app-container">
    <div class="main">
      <div class="warehouse_left">
        <div class="filter_warecontainer">
          <el-form :inline="true" :model="warehouseFromData">
            <el-form-item label="城市">
              <el-select
                v-model="warehouseFromData.cityId"
                ref="cityIdRef"
                size="small"
                style="width: 130px"
                clearable
                placeholder="请选择城市"
                @keydown.native="selectBlur($event)"
              >
                <el-option
                  v-for="item in cityList"
                  :key="item.id"
                  size="small"
                  :label="item.deptName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="区域">
              <el-select
                v-model="warehouseFromData.deptId"
                size="small"
                ref="deptIdRef"
                clearable
                style="width: 130px"
                placeholder="请选择区域"
                @visible-change="getareadataList"
                @keydown.native="selectBlur($event)"
              >
                <el-option
                  v-for="item in areadataList"
                  :key="item.id"
                  size="small"
                  :label="item.deptName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="仓库名称">
              <el-input
                v-model="warehouseFromData.name"
                ref="nameRef"
                @visible-change="getwarehousename"
                @keydown.native="selectBlur($event)"
                size="small"
              >
              </el-input>
              <!-- <el-select
                v-model="name"
                ref="nameRef"
                size="small"
                clearable
                filterable
                style="width: 150px;"
                placeholder="请选择仓库名称"
                @visible-change="getwarehousename"
                @change="getwarehousenameIds"
                @keydown.native="selectBlur($event)"
              >
                <el-option
                  v-for="item in warehousenameList"
                  :key="item"
                  size="small"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select> -->
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                plain
                size="small"
                icon="el-icon-search"
                @click="handleFilter"
                >查询</el-button
              >
              <el-button
                v-xmbz-permission="'warehous_add'"
                type="success"
                plain
                size="small"
                icon="el-icon-circle-plus-outline"
                @click="handleAddwarehouse"
                >新增仓库</el-button
              >
              <el-button
                v-xmbz-permission="'warehouse_edit'"
                type="success"
                plain
                size="small"
                @click="handleBatchEditTime"
                >批量修改配送时间</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="warehousetablist">
          <span
            class="name"
            v-for="(item, index) in tabs"
            :class="{ active: indexs == index }"
            @click="handleTabs(index)"
            :key="index"
            >{{ item.name }}</span
          >
        </div>
        <div class="warehouse_list">
          <el-table :data="warehouselist" border style="width: 100%" ref="warehouseTable">
            <el-table-column
              fixed
              type="selection"
            ></el-table-column>
            <el-table-column
              fixed
              prop="id"
              label="ID"
              width="100"
            ></el-table-column>
            <el-table-column prop="deptName" label="区域"></el-table-column>
            <el-table-column
              prop="address"
              label="仓库地址"
              width="100"
            ></el-table-column>
            <el-table-column prop="name" label="仓库名称"></el-table-column>
            <el-table-column
              prop="isUp"
              label="开始接单(1关闭,2开启)"
            ></el-table-column>
            <el-table-column
              prop="orderAdvanceTime"
              label="下单提前时间(分钟)"
            ></el-table-column>
            <el-table-column
              prop="wareHouseType"
              label="仓库类型"
            ></el-table-column>
            <el-table-column
              prop="salesOrganizationId"
              label="销售组织ID"
            ></el-table-column>
            <el-table-column
              prop="salesOrganizationName"
              label="销售组织名称"
            ></el-table-column>
            <el-table-column label="中央厨房">
              <template slot-scope="scope">
                {{
                  scope.row.kitchenName || changeNumber(scope.row.kitchenName)
                }}
              </template>
            </el-table-column>
            <el-table-column label="生产站">
              <template slot-scope="scope">
                {{
                  scope.row.productionName ||
                  changeNumber(scope.row.productionName)
                }}
              </template>
            </el-table-column>
            <el-table-column label="中转仓">
              <template slot-scope="scope">
                {{
                  scope.row.transferName || changeNumber(scope.row.transferName)
                }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="{ row, $index }">
                <div class="oprate-btns">
                  <el-button
                    v-xmbz-permission="'warehouse_edit'"
                    type="text"
                    size="small"
                    @click.native="handleUpdate($index, row)"
                    >编辑仓库</el-button
                  >
                  <el-button
                    v-xmbz-permission="'warehouse_del'"
                    type="text"
                    size="small"
                    @click.native="handleDelete($index, row)"
                    >删除仓库</el-button
                  >
                  <el-button
                    v-xmbz-permission="'warehouse_Setup'"
                    type="text"
                    size="small"
                    @click.native="handleSetclose($index, row)"
                    >设置</el-button
                  >
                </div>
                <!-- <el-button type="text" size="small" @click.native="handleWarehouseload($index, row)" style="margin-left: 0!important;">仓库负荷</el-button> -->
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            layout="sizes,prev, pager, next,total"
            :page.sync="warehouseFromData.page"
            :limit.sync="warehouseFromData.size"
            @pagination="getList"
          />
        </div>
      </div>
      <div class="warehouse_right">
        <XmMap ref="xmMap" style="width: 100%;height: 100%;"
          :options="{ id: 'warehoseSystemMap'}" :hasScreenBtn="true"></XmMap>
      </div>
    </div>
    <!-- 新增仓库 -->
    <el-dialog
      title="新增仓库"
      :visible.sync="warehouseVisible"
      width="80%"
      :before-close="handleClose"
    >
      <warehouse
        ref="warehouse"
        @close="handelDialogReset"
        @getList="getList"
      ></warehouse>
      <!-- <warehousEidt v-if="dialogStatus=='update'" ref="warehouse" v-bind:detaillist="detaillist"></warehousEidt> -->
    </el-dialog>
    <el-dialog
      title="修改仓库"
      :visible.sync="warehouseEditVisible"
      width="80%"
      :before-close="handleCloseEdit"
    >
      <warehousEidt
        ref="warehousEidt"
        @close="handelDialogReset"
        @getList="getList"
      ></warehousEidt>
      <!-- <load></load> -->
    </el-dialog>
    <!-- 编辑负荷 -->
    <el-dialog
      title="仓库负荷"
      :visible.sync="loadVisible"
      width="90%"
      :before-close="handleClose"
    >
      <load
        :allList="allList"
        @close="handeloadVisible"
        @getList="getList"
      ></load>
    </el-dialog>
    <!-- 设置关闭仓库 -->
    <el-dialog
      title="熊猫不走蛋糕-接单设置"
      :visible.sync="closeorderVisible"
      width="60%"
      :before-close="handlecloseorder"
    >
      <closeorder
        :closeId="closeId"
        @closeorder="handelcloseorder"
      ></closeorder>
    </el-dialog>

    <setDeliveryTimeDialog ref="setDeliveryTimeDialog" @confirm="handleSetDelivery"></setDeliveryTimeDialog>
  </basic-container>
</template>
<script>
import Pagination from "@/components/Pagination"; // 分页
import load from "@/components/warehouse/load";
import warehouse from "@/components/warehouse/warehouse";
import warehousEidt from "@/components/warehouse/warehousEidt";
import closeorder from "@/components/warehouse/closeorder";
import setDeliveryTimeDialog from "@/components/warehouse/setDeliveryTimeDialog";
import {
  deptdepts,
  selectDeptByCityId,
  getWarehousePage,
  getWarehouseName,
  warehouseelete,
  getWarehouseList,
  getWarehouseByType, //  平台仓
  batchUpdateWarehouseDeliveryTime,
} from "@/api/warehouse";
// import VueAMap from "vue-amap";
import { getWarehouseLabel } from '@/util/map'

export default {
  components: {
    Pagination,
    load,
    warehouse,
    warehousEidt,
    closeorder,
    setDeliveryTimeDialog
  },
  data() {
    const cityId = JSON.parse(localStorage.getItem("saber-areaId")) && JSON.parse(localStorage.getItem("saber-areaId")).content
    return {
      kitchenMarks: [], // 位置列表
      mapGeoList: [], // 经纬度列表
      warehouseFromData: {
        cityId: cityId,
        deptId: '', //仓库名称
        name: '', //仓库名称
        page: 1, //页码
        size: 10, //每页页码
      },
      indexs: -1,
      tabs: [
        //标签数据
        {
          name: "显示配送区域",
        },
        {
          name: "显示行政区域",
        },
      ],

      total: 0,
      cityList: [],
      areadataList: [], //区域

      warehousenameList: [], //仓库名称
      warehouselist: [],
      detaillist: {},
      // 负荷---------------------------------------
      loadVisible: false,
      warehouseVisible: false,
      warehouseEditVisible: false,
      //行政区域
      allList: "",
      // 关闭接单
      closeorderVisible: false,
      closeId: "",
    };
  },
  watch: {
    warehouseVisible() {
      if (this.warehouseVisible == true) {
        window.removeEventListener("keydown", this.keyupEnter);
      } else {
        window.addEventListener("keydown", this.keyupEnter);
      }
    },
    warehouseEditVisible() {
      if (this.warehouseEditVisible == true) {
        window.removeEventListener("keydown", this.keyupEnter);
      } else {
        window.addEventListener("keydown", this.keyupEnter);
      }
    },
  },
  mounted() {
    var saberareaIds = JSON.parse(localStorage.getItem("saber-areaId"));
    this.citydataList()
    this.getList();
    window.addEventListener("keydown", this.keyupEnter);
  },
  destroyed() {
    window.removeEventListener("keydown", this.keyDown, false);
  },
  methods: {
    changeNumber(item) {
      return item > 0 ? item : "";
    },
    // 回车事件
    selectBlur(e) {
      if (e.keyCode == 13) {
        this.$refs["cityIdRef"].blur();
        this.$refs["deptIdRef"].blur();
        this.$refs["nameRef"].blur();
        e.returnValue = false;
      }
    },
    keyupEnter() {
      if (window.event.keyCode == 13) {
        this.handleFilter(); // 查询事件
      }
    },
    //如果页面有keep-alive缓存功能，这个函数会触发
    activated() {
      window.addEventListener("keydown", this.keyupEnter);
    },
    deactivated() {
      window.removeEventListener("keydown", this.keyupEnter);
    },
    getList() {
      getWarehousePage(this.warehouseFromData).then((response) => {
        this.warehouselist = response.data.data.rows;
        this.total = response.data.data.total;
        if (this.warehouselist && this.warehouselist.length) {
          this.clearMap()
          this.addWarehoseMarkerOnMap(this.warehouselist)
          this.setCenter()
        } else {
          this.$message({
            showClose: true,
            message: "暂无数据",
            type: "warning",
          });
        }
      });
    },
    // 添加仓库marker
    addWarehoseMarkerOnMap(datas) {
      this.warehouseMarkers = datas.map(item => {
        const m = this.$refs.xmMap.createMarker({
          longitude: item.longitude,
          latitude: item.latitude,
          label: {
            content: `<div class='info'>${item.name}</div>`
          },
        })
        this.$refs.xmMap.map.add(m);
        return m
      })
      return this.warehouseMarkers
    },
    // 根据覆盖物居中
    setCenter() {
      const overlays = this.$refs.xmMap.map.getAllOverlays()
      this.$refs.xmMap.setFitView(overlays);
    },

    clearMap() {
      this.$refs.xmMap.clearMap()
    },

    citydataList() {
      //获取城市列表数据
      deptdepts("").then((response) => {
        this.cityList = response.data.data;
      });
    },

    getareadataList() {
      //区域下拉
      if (!this.warehouseFromData.cityId) {
        this.$message({
          showClose: true,
          message: "请选择城市",
          type: "warning",
        });
      } else {
        selectDeptByCityId({
          cityId: this.warehouseFromData.cityId,
        }).then((res) => {
          this.areadataList = res.data.data;
        });
      }
    },
    getwarehousename() {
      //仓库名称下拉
      if (!this.warehouseFromData.cityId || this.warehouseFromData.cityId != 0) {
        this.$message({
          showClose: true,
          message: "请选择城市",
          type: "warning",
        });
      } else if (!this.warehouseFromData.deptId) {
        this.$message({
          showClose: true,
          message: "请选择区域",
          type: "warning",
        });
      } else {
        getWarehouseName({
          cityId: this.warehouseFromData.cityId,
          deptId: this.warehouseFromData.deptId,
        }).then((response) => {
          this.warehousenameList = response.data.data;
        });
      }
    },
    handleFilter() {
      //查询
      this.warehouseFromData.page = 1;
      this.getList();
      this.indexs = "-1";
    },
    handleAddwarehouse() {
      //添加仓库
      this.warehouseVisible = true;
    },
    // 提交
    handleUpdate(index, row) {
      //编辑仓库
      this.warehouseEditVisible = true;
      this.$nextTick(() => {
        this.$refs.warehousEidt.getArea(row)
      })
    },
    handleDelete(index, row) {
      window.removeEventListener("keydown", this.keyupEnter);
      // 删除仓库
      this.$confirm("确定删除该仓库?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        closeOnClickModal: false,
        //阻止键盘点击回车事件
        beforeClose(action, instance, done) {
          // console.log(action,instance)
          if (action == "confirm") {
            instance.$refs["confirm"].$el.onclick = function (e) {
              e = e || window.event;
              console.log(e.detail);
              if (e.detail != 0) {
                done();
                warehouseelete({
                  id: row.id,
                }).then(() => {
                  this.$message({
                    type: "success",
                    message: "操作成功!",
                  });
                  setTimeout(() => {
                    this.getList();
                    this.listLoading = false;
                  }, 1.5 * 1000);
                });
              }
            };
          } else {
            done();
            warehouseelete({
              id: row.id,
            }).then(() => {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              setTimeout(() => {
                this.getList();
                this.listLoading = false;
              }, 1.5 * 1000);
            });
          }
        },
      })
        .then(() => {})
        .catch(() => {});
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          this.warehouseVisible = false;
          done();
        })
        .catch(() => {});
    },

    handleWarehouseload(index, row) {
      //仓库负荷
      if (row.deliveryStartTime == "") {
        this.$message({
          showClose: true,
          message: "请先设置配送开始时间",
          type: "warning",
        });
      } else if (row.deliveryEndTime == "") {
        this.$message({
          showClose: true,
          message: "请先设置配送结束时间",
          type: "warning",
        });
      } else {
        this.loadVisible = true;
        this.allList = row;
      }
    },

    handleTabs(item) {
      //行政区域问题
      this.indexs = item;
      if (!this.warehouseFromData.cityId) {
        this.$message({
          showClose: true,
          message: "请选择城市",
          type: "warning",
        });
        return
      }
      if (this.indexs == 1) {
        this.clearMap()
        //行政区查询
        this.addDistrictOnMap().then((polygon) => {
          this.setCenter()
        })
        this.addWarehoseMarkerOnMap(this.warehouselist)
      }
      if (this.indexs == "0") {
        this.clearMap()
        this.addWarehouseOnMap().then(() => {
          this.setCenter()
        })
        this.addPlatformWarehouseOnMap()
      }
    },
    // 添加行政区域
    async addDistrictOnMap() {
      if (!this.districtSearch) {
        this.districtSearch = await this.$refs.xmMap.districtSearchPlugin()
      }
      this.districtPolygon = await this.$refs.xmMap.getDistrictPolygon(this.getCityName())
      this.$refs.xmMap.map.add([this.districtPolygon]);
      return this.districtPolygon
    },
    // 添加仓库配送范围
    addWarehouseOnMap() {
      const params = {
        name: this.warehouseFromData.name,
        deptId: this.warehouseFromData.deptId,
        cityId: this.warehouseFromData.cityId,
      };
      return getWarehouseList(params).then(res => {
        const resData = res.data.data || [];
        if (resData && resData.length) {
          const markers = resData.map(item => {
            return this.$refs.xmMap.createMarker({
              longitude: item.longitude,
              latitude: item.latitude,
              label: {
                content: getWarehouseLabel(item)
              },
            })
          });
          const polygonPath = resData.map(item => {
            return item.geoJson.geometry.coordinates[0]
          })
          const polygon = this.$refs.xmMap.createPolygon({
            path: polygonPath,
            strokeColor: "#FF33FF",
            strokeWeight: 2,
            fillOpacity: 0.2,
            fillColor: "#1791fc",
            zIndex: 50,
          });
          this.$refs.xmMap.map.add([...markers, polygon])
        }
      })
      // getWarehouseByType({ cityId: this.warehouseFromData.cityId, type: 99 }).then(
    },
    // 添加平台仓
    addPlatformWarehouseOnMap() {
      const params = {
        type: 99,
        cityId: this.warehouseFromData.cityId,
      };
      return getWarehouseList(params).then(res => {
        const resData = res.data.data || [];
        if (resData && resData.length) {
          const markers = resData.map(item => {
            return this.$refs.xmMap.createMarker({
              longitude: item.longitude,
              latitude: item.latitude,
              label: {
                content: getWarehouseLabel(item)
              },
            })
          });
          const polygonPath = resData.map(item => {
            return item.geoJson.geometry.coordinates[0]
          })
          const polygon = this.$refs.xmMap.createPolygon({
            path: polygonPath,
            strokeColor: "#00FF7F",
            strokeWeight: 2,
            fillOpacity: 0.2,
            fillColor: "#FF8C00",
            zIndex: 100,
          });
          this.$refs.xmMap.map.add([...markers, polygon])
        }
      })
      // getWarehouseByType({ cityId: this.warehouseFromData.cityId, type: 99 }).then(
    },

    getCityName() {
      const cityItem = this.cityList.find(item => item.id == this.warehouseFromData.cityId)
      return cityItem && cityItem.deptName
    },

    handelDialogReset() {
      this.warehouseVisible = false;
      this.warehouseEditVisible = false;
    },
    handleCloseEdit() {
      this.$confirm("确认关闭？")
        .then(() => {
          this.closeId = "";
          this.warehouseEditVisible = false;
        })
        .catch(() => {});
    },
    handeloadVisible() {
      this.loadVisible = false;
    },
    // 设置
    handleSetclose(index, row) {
      this.closeId = row.id;
      this.closeorderVisible = true;
    },
    handlecloseorder() {
      this.$confirm("确认关闭？")
        .then(() => {
          this.closeId = "";
          this.closeorderVisible = false;
        })
        .catch(() => {});
    },
    handelcloseorder() {
      this.closeorderVisible = false;
    },
    handleBatchEditTime() {
      const selections = this.$refs.warehouseTable.selection
      if (selections && selections.length) {
        this.$refs.setDeliveryTimeDialog.show([])
      } else {
        this.$message({
          type: 'warning',
          message: '请先勾选表格记录！'
        })
      }
    },
    handleSetDelivery(deliveryTimes) {
      const selections = this.$refs.warehouseTable.selection
      const params = {
        "warehouseIds": selections.map(item => item.id),
        "warehouseDeliveryTimes": deliveryTimes
      }
      batchUpdateWarehouseDeliveryTime(params).then(res => {
        if (res.data.code == 200) {
          this.$message({
            type: 'success',
            message: '修改成功！'
          })
          this.$refs.setDeliveryTimeDialog.hide()
          this.getList();
        }
      })
    }
  },
};
</script>

<style lang='scss' scoped>
.infoplatform{
  color: #EC2C2C;
}
.app-container {
  .el-form {
    display: block !important;
  }

  .main {
    background: #fff;
    display: flex;
    justify-content: space-between;

    .warehouse_left {
      padding: 20px;
      width: 45%;
      border-radius: 4px;
      border: 1px solid #ebeef5;
      background-color: #fff;
      overflow: hidden;
      color: #606266;
      transition: 0.3s;
      margin-bottom: 10px;

      .el-table td {
        padding: 2px 0 !important;

        .el-button--small {
          padding: 2px;
        }
      }

      .warehousetablist {
        margin-bottom: 20px;

        span {
          border: 1px solid #dcdfe6;
          padding: 6px 8px;
          cursor: pointer;
          margin-right: 5px;
          border-radius: 4px;
          font-size: 14px;

          &.active {
            color: #fff;
            background-color: #43a0ff;
            border-bottom: 1px solid #43a0ff;
          }
        }
      }

      .filter_warecontainer {
        .el-form {
          display: block !important;
        }

        .el-form-item {
          margin-bottom: 10px !important;
        }
      }

      .oprate-btns {
        .el-button {
          padding: 2px;
          display: block;
          margin: 0;
        }
      }
    }

    .warehouse_right {
      width: 50%;
      min-height: 600px;
      box-shadow: rgb(223, 228, 237) 2px 2px 10px;
    }
  }
}
</style>
